package cn.gov.cbrc.core.servlet;

import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import cn.gov.cbrc.core.util.PropertiesUtil;

/**
 * 日志查询
 */
public class QueryLogDetail extends HttpServlet {
	private static final long serialVersionUID = 1L;
	/*每页日志大小*/
	//private static int pageSize = 50;
       
    public QueryLogDetail() {
        super();
    }

	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		this.doPost(request, response);
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		//request.setCharacterEncoding("GBK");
		response.setContentType("text/html;charset=UTF-8");
		PrintWriter out = response.getWriter();
		String logName = request.getParameter("logName");
		//页码
		int pageNo = Integer.parseInt(request.getParameter("page"));
		int pageSize = Integer.parseInt(request.getParameter("rows"));
		JSONObject json = new JSONObject();
		JSONArray logArr = new JSONArray();
		String logPath = PropertiesUtil.getProperty("logPath");
		String file = logPath+"/"+logName;
		String str = null;
		HttpSession session = request.getSession();
		List<String> logList = (List<String>) session.getAttribute(file+"_LOG_LIST");
		if(logList == null){
			BufferedReader bre = null;
			try {
				bre = new BufferedReader(new InputStreamReader(new FileInputStream(file),"UTF-8"));
				logList = new ArrayList<String>();
				while((str = bre.readLine())!=null){
					logList.add(str);
				}
				session.setAttribute(file+"_LOG_LIST", logList);
			} catch (Exception e) {
				e.printStackTrace();
			}finally{
				bre.close();
			}
		}
		int startNo = (pageNo-1)*pageSize;
		int endNo = pageNo*pageSize-1;
		if(endNo > logList.size()-1){
			endNo = logList.size() - 1;
		}
		for(int i=startNo;i<=endNo;i++){
			logArr.add("{\"logDetail\":\""+logList.get(i)+"\"}");
		}
		json.put("total", logList.size());
		json.put("rows", logArr);
		out.print(json);
		out.close();
	}

}
